<template>
  <div class="app-container">
    <span style="font-size: medium;color: rgba(151,170,195) "> / 采购订单 / 订单生成 / 生成采购订单</span>

    <el-row style="margin-top: 20px">
      <el-col :span="10" class="card-box">
        <el-card>
          <template #header><Monitor style="width: 1em; height: 1em; vertical-align: middle;" /> <span style="vertical-align: middle;">采购基本信息</span></template>
          <div class="el-table el-table--enable-row-hover el-table--medium">
            <table style="width: 100%;">
              <tbody>
              <tr>
                <td class="el-table__cell is-leaf"><div class="cell">采购订单编号</div></td>
                <td class="el-table__cell is-leaf">
                  <div class="cell"
                       style="margin-top: 4.5px;margin-bottom: 4.5px"
                  >{{orderInfo.orderNo}}</div>
                </td>
              </tr>
              <tr>
                <td class="el-table__cell is-leaf"><div class="cell">下单时间</div></td>
                <td class="el-table__cell is-leaf">
                  <div class="cell"
                       style="margin-top: 6px;margin-bottom: 6px"
                  >{{orderInfo.orderTime}}</div>
                </td>
              </tr>
              <tr>
                <td class="el-table__cell is-leaf"><div class="cell">勾选货品</div></td>
                <td class="el-table__cell is-leaf">
                  <div class="cell"
                       style="margin-top: 13.5px;margin-bottom: 13.5px"
                  >{{productsNum}} 种</div>
                </td>
              </tr>
              </tbody>
            </table>
          </div>
        </el-card>
      </el-col>

      <el-col :span="14" class="card-box">
        <el-card>
          <template #header><Setting style="width: 1em; height: 1em; vertical-align: middle;" /> <span style="vertical-align: middle;">采购信息填写</span></template>
          <div class="el-table el-table--enable-row-hover el-table--medium">
            <table style="width: 100%;">
              <tbody>
              <tr>
                <td class="el-table__cell is-leaf" style="width: 15%"><div class="cell">*供货商</div></td>
                <td class="el-table__cell is-leaf" style="width: 30%">
                  <el-select style="width: 60%;" v-model="orderInfo.companyName" @change="handleSupplierChange">
                    <el-option
                        v-for="item in suppliers"
                        :key="item"
                        :label="item"
                        :value="item"
                    />
                  </el-select>
                </td>
                <td class="el-table__cell is-leaf" style="width: 15%"><div class="cell">*收货地址</div></td>
                <td class="el-table__cell is-leaf" >
                  <el-select v-model="orderInfo.deliveryAddress" placeholder="请选择交货地点" style="width: 100%" @change="handleSelectedAddressChange">
                    <el-option
                        v-for="item in addressList"
                        :key="item.code"
                        :label="formatAddress(item)"
                        :value="item.name"
                    />
                  </el-select>
                </td>
              </tr>
              <tr>
                <td class="el-table__cell is-leaf" style="width: 18%"><div class="cell">*采购负责人</div></td>
                <td class="el-table__cell is-leaf" style="width: 30%">
                  <el-input
                      style="width: 80%"
                      v-model="orderInfo.responsiblePerson"
                      placeholder="请选择采购负责人"
                      clearable
                  />
                </td>
                <td class="el-table__cell is-leaf" style="width: 20%"><div class="cell">*联系电话</div></td>
                <td class="el-table__cell is-leaf">
                  <el-input
                      v-model="orderInfo.contactPhone"
                      placeholder="请输入联系电话"
                      clearable
                  />
                </td>
              </tr>
              <tr>
                <td class="el-table__cell is-leaf" style="width: 15%"><div class="cell">备注</div></td>
                <td class="el-table__cell is-leaf" :colspan="2">
                  <el-input
                      v-model="orderInfo.remarks"
                      placeholder="请填写备注"
                      type="textarea"
                      clearable
                  />
                </td>
              </tr>
              </tbody>
            </table>
          </div>
        </el-card>
      </el-col>

      <el-col :span="24" class="card-box">
        <el-card>
          <template #header><Goods style="width: 1em; height: 1em; vertical-align: middle;" /> <span style="vertical-align: middle;">采购货品信息</span></template>
          <div class="el-table el-table--enable-row-hover el-table--medium">
            <el-table v-loading="loading" :data="showProductForm">
              <el-table-column label="采购明细编号" align="center" prop="orderDetailNo" width="180" fixed/>
              <el-table-column label="货品批号" align="center" prop="rawProductBatch" width="120"/>
              <el-table-column label="货品名称" align="center" prop="name"/>
              <el-table-column label="货品单价(元/吨)" align="center" prop="unitPrice" width="120"/>
              <el-table-column label="需求数量(吨)" align="center" width="100">
                <template #default="scope">
                  <span>{{getDefaultNum(scope.row.name) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="订购数量(吨)" align="center" width="180">
                <template #default="scope">
                  <el-input-number v-model="scope.row.orderNum" :precision="2" controls-position="right" @change="handlePurchaseQuantityChange"/>
                </template>
              </el-table-column>
              <el-table-column label="预期到货时间" align="center" width="180">
                <template #default="scope">
                  <el-date-picker
                      v-model="scope.row.expectedDeliveryTime"
                      placeholder="请选择时间"
                      format="YYYY/MM/DD"
                      value-format="YYYY-MM-DD"
                      style="width: 90%;"
                  />
                </template>
              </el-table-column>
              <el-table-column label="小计(元)" align="center">
                <template #default="scope">
                  <span >{{scope.row.orderNum !== undefined? scope.row.orderNum * scope.row.unitPrice : 0}}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
                <template #default="scope">
                  <el-button link type="primary" icon="View" @click="showDetail(scope.row)">详情</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div style="display: flex;justify-content: right;margin-top: 10px;margin-right: 20px">
              <span style="font-size: large">总计：￥{{totalPrice}}</span>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="24">
        <div style="display: flex; justify-content: right;
                margin-top: 30px; margin-right: 20px;gap: 10px">
          <el-button
              round
              icon="Back"
              class="custom-large-button"
              @click="handleBack"
          >返回</el-button>
          <el-button
              type="primary"
              round
              icon="Pointer"
              class="custom-large-button"
              @click="handleOrderGenerate"
          >提交</el-button>
        </div>
      </el-col>
    </el-row>

    <!-- 货品详情 -->
    <el-dialog title="货品详情" v-model="open" width="700px" append-to-body>
      <el-form :model="form" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="供货商名称：">{{form.companyName}}</el-form-item>
            <el-form-item label="保质期：">{{form.shelfLife}} (天)</el-form-item>
            <el-form-item label="原产地：">{{form.origin}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="货品名称：">{{form.name}}</el-form-item>
            <el-form-item label="货品种类：">{{form.goodsCategory}}</el-form-item>
            <el-form-item label="温度要求：">{{form.storageTemperature}}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="货品图片：" showTip="false">
              <el-image :src="form.picture" style="width: 150px; height: 150px;" fit="cover"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="货品描述：">{{form.description}}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="货品规格：">{{form.specification}}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="价格信息：">{{form.priceInformation}}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注：">{{form.remarks}}</el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div style="margin-top: -40px">
          <el-button @click="open = false" type="primary">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="DetailOrder">

import { useRouter } from "vue-router";
import { updatePurchasePlan, getPurchasePlanList } from "@/api/purchase/purchasePlan.js";
import { getProducts, getSupplierList } from "@/api/purchase/rawProduct.js";
import { addPurchaseOrder } from "@/api/purchase/purchaseOrder.js"
import { addOrderDetail } from "@/api/purchase/orderDetail.js"
import {addPlanOrderLinkList} from "@/api/purchase/PlanOrderLink.js";
import AMapLoader from "@amap/amap-jsapi-loader";
import {listDictDataAll} from "@/api/purchase/DictData.js";

const { proxy } = getCurrentInstance();

const router = useRouter();
const selectedProducts = ref([]); // 记录选择的货品
const productsNum = ref(0); // 记录选择货品的种类数
const suppliers =ref([]); // 记录所有的供货商
const rawProductForm = ref([]); // 记录所有的货品信息
const showProductForm = ref([]); // 展示特定供货商的货品
const loading = ref(false); // 展示图片是否正在加载
const open = ref(false); // 控制详情展示对话框显示
const form = ref({}); // 详情展示
const planNoList = ref([]) // 选中计划
const planInfo = ref({})
const orderDetails = ref([])
const totalPrice = ref(0.0);
const addressList = ref([]) //可选的收货地址
const orderInfo = ref({
  orderNo: generateOrderNumber(),
  orderTime: '',
  companyName: '',
  deliveryAddress: null,
  destinationLng: null,
  destinationLat: null,
  expectedDeliveryTime: null,
  totalAmount: 0.0,
  currencyUnit: '元',
  contactPhone: null,
  responsiblePerson: null,
  remarks: ''
});

/** 初始化 **/
function initial() {
  if(proxy.$route.query.planNoList){
    let list = proxy.$route.query.planNoList;
    if(!Array.isArray(list)){
      list = [list]
    }
    planNoList.value = list;
    getPurchasePlanList(planNoList.value).then(response => {
      planInfo.value = response.data;
      selectedProducts.value = planInfo.value.map(item => item.rawProductName);
      productsNum.value = selectedProducts.value.length;

      //初始化供货商信息
      getSupplierList(selectedProducts.value).then(response => {
        suppliers.value = response.data;
        orderInfo.value.orderTime = getFormattedTime();
        orderInfo.value.companyName = suppliers.value[0];

        //初始化货品信息
        loading.value = true
        getProducts(selectedProducts.value).then(response => {
          rawProductForm.value = response.data;
          showProductForm.value = rawProductForm.value.filter(
              item => item.companyName === orderInfo.value.companyName);
          showProductForm.value.forEach((item, index) => {
            item.orderDetailNo = orderInfo.value.orderNo + '-'
                + String(index+1).padStart(3, '0')
            item.rawProductBatch = generateBatchNumber();
          });
          loading.value = false;
        });
      });
    })

    //获取地址信息
    const query = {type: '收货地址'}
    listDictDataAll(query).then(response => {
      addressList.value = response.data;
    })
  }
}

/** 获取当前时间 **/
function getFormattedTime(){
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

/** 获取默认购买数量 **/
function getDefaultNum(name) {
  for(let i = 0; i < productsNum.value; i++) {
    let item = planInfo.value[i];
    if(item.rawProductName === name) {
      return item.quantity -item.purchaseQuantity > 0 ?
          item.quantity -item.purchaseQuantity : 0;
    }
  }
}

/** 选择框选中的供货商变化 **/
function handleSupplierChange(supplier) {
  loading.value = true;
  showProductForm.value = rawProductForm.value.filter(
      item => item.companyName === supplier);
  showProductForm.value.forEach(item => {
    item.rawProductBatch = generateBatchNumber();
    initial();
  });
  loading.value = false;
}

/** 展示货品详情 **/
function showDetail(row) {
  open.value = true;
  form.value = row;
}

/** 生成订单 **/
function handleOrderGenerate() {
  if(!checkOrder()){
    return;
  }
  //添加订单
  addPurchaseOrder(orderInfo.value).then(response => {
    //设置订单详情
    setDetailOrder();
    for(let i = 0; i < productsNum.value; i++) {
      addOrderDetail(orderDetails.value[i]);
    }
    proxy.$modal.msgSuccess("新增成功");
  });
  //修改采购计划
  setOrderAmount();
  for(let i = 0; i < productsNum.value; i++) {
    updatePurchasePlan(planInfo.value[i]);
  }
  //插入采购计划与订单关联
  addPlanOrderLink();
  handleBack();
}

/** 提交订单判断 **/
function checkOrder(){
  if(orderInfo.value.companyName === ""||
      orderInfo.value.companyName == null){
    proxy.$modal.msgError("供货商不能为空");
    return false;
  }
  else if(orderInfo.value.responsiblePerson === ""||
      orderInfo.value.responsiblePerson == null){
    proxy.$modal.msgError("负责人不能为空");
    return false;
  }
  else if(orderInfo.value.contactPhone === ""||
      orderInfo.value.contactPhone == null){
    proxy.$modal.msgError("联系电话不能为空");
    return false;
  }
  else if(orderInfo.value.deliveryAddress === ""||
      orderInfo.value.deliveryAddress == null){
    proxy.$modal.msgError("收货地址不能为空");
    return false;
  }
  for(let i = 0; i < productsNum.value; i++){
    if(showProductForm.value[i].orderNum <= 0){
      proxy.$modal.msgError("采购数量必须大于0");
      return false;
    }
    if(showProductForm.value[i].expectedDeliveryTime === undefined ||
        showProductForm.value[i].expectedDeliveryTime === null){
      proxy.$modal.msgError("预期送达时间不能为空");
      return false;
    }
  }
  return true;
}

/** 获取每个货品的订购数量 **/
function setOrderAmount(){
  for(let i = 0; i < productsNum.value; i++) {
    let orderAmount = showProductForm.value[i].orderNum;
    let rawProductName = showProductForm.value[i].name;
    for(let j = 0; j < productsNum.value; j++) {
      if(planInfo.value[j].rawProductName === rawProductName){
        planInfo.value[j].purchaseQuantity += orderAmount;
        planInfo.value[j].planStatus = '已执行';
        if(planInfo.value[j].purchaseQuantity < planInfo.value[j].quantity){
          planInfo.value[j].purchaseStatus = '部分完成';
        }
        else if(planInfo.value[j].purchaseQuantity === planInfo.value[j].quantity){
          planInfo.value[j].purchaseStatus = '全部完成';
        }
        else if(planInfo.value[j].purchaseQuantity > planInfo.value[j].quantity){
          planInfo.value[j].purchaseStatus = '超额完成';
        }
        break;
      }
    }
  }
}

/** 设置订单详情 **/
function setDetailOrder(){
  orderDetails.value = showProductForm.value;
  let orderNo = orderInfo.value.orderNo;
  for(let i = 0; i < productsNum.value; i++) {
    orderDetails.value[i].orderNo = orderNo;
    orderDetails.value[i].quantity = showProductForm.value[i].orderNum;
    orderDetails.value[i].rawProductName = showProductForm.value[i].name;
  }
}

/** 退出 **/
function handleBack(){
  proxy.$tab.closeOpenPage(router.currentRoute.value);
  proxy.$router.push({
    path:'/Purchase/PurchaseOrder/OrderGenerate',
  });
}

/** 随机生成订单编号 **/
function generateOrderNumber() {
  // 定义字符集，可以根据需要调整
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  let orderNumber = '';
  for (let i = 0; i < 10; i++) {
    const randomIndex = Math.floor(Math.random() * chars.length);
    orderNumber += chars[randomIndex];
  }
  return orderNumber;
}

/** 随机生成货品批号 **/
function generateBatchNumber() {
  // 定义字符集，可以根据需要调整
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  let batchNumber = '';
  for (let i = 0; i < 6; i++) {
    const randomIndex = Math.floor(Math.random() * chars.length);
    batchNumber += chars[randomIndex];
  }
  return 'RP' + batchNumber;
}

function addPlanOrderLink(){
  let links = [];
  for (let i= 0; i < planInfo.value.length; i++) {
    for (let j = 0; j < showProductForm.value.length; j++){
      if (planInfo.value[i].rawProductName === showProductForm.value[j].name) {
        links.push({
          planNo: planInfo.value[i].planNo,
          rawProductBatch: showProductForm.value[j].rawProductBatch,
        })
      }
    }
  }
  addPlanOrderLinkList(links);
}

function handlePurchaseQuantityChange() {
  totalPrice.value = showProductForm.value.reduce((total, item) => {
    if(item.orderNum === undefined){
      return total;
    }
    return total + item.orderNum * item.unitPrice;
  }, 0);
}

/** 格式化订单交货地点的选择 */
function formatAddress(item) {
  return item.name + " - " + item.person + " - " + item.contact;
}

/** 选择交货地点后为负责人和联系电话赋值 */
function handleSelectedAddressChange(value){
  if(value){
    addressList.value.forEach(item => {
      if(item.name === value){
        orderInfo.value.responsiblePerson = item.person;
        orderInfo.value.contactPhone = item.contact;
        orderInfo.value.destinationLng = item.lng;
        orderInfo.value.destinationLat = item.lat;
      }
    })
  }
}

initial()
</script>